<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="文件名称" prop="fileName">
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入文件名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="存储地址" prop="fileDopath">
        <el-input
          v-model="queryParams.fileDopath"
          placeholder="请输入存储地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">

      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"

        >修改
        </el-button>
<!--        v-hasPermi="['system:info:edit']"-->
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"

        >删除
        </el-button>
<!--        v-hasPermi="['system:info:remove']"-->
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleImport"

        >导入工程
        </el-button>
<!--        v-hasPermi="['system:info:export']"-->
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange" ref="multipleTable" @row-click="handleRowClick">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="文件名称" align="center" prop="fileName"/>
      <el-table-column label="存储地址" align="center" prop="fileDopath"/>
      <el-table-column label="导入时间" align="center" prop="createTime"/>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!--          <el-button-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-edit"-->
          <!--            @click="handleUpdate(scope.row)"-->
          <!--            v-hasPermi="['system:info:edit']"-->
          <!--          >修改</el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"

          >删除
          </el-button>
<!--          v-hasPermi="['system:info:remove']"-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改文件上传对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body class="my_dialog" >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文件名称" prop="fileName">
          <el-input v-model="form.fileName" placeholder="请输入文件名称"/>
        </el-form-item>
        <el-form-item label="存储地址" prop="fileDopath">
          <el-input v-model="form.fileDopath" placeholder="请输入存储地址"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="700px"
               append-to-body v-loading="loading"
               element-loading-text="文件上传中，请稍后"
               element-loading-spinner="el-icon-loading"
               element-loading-background="rgba(0, 0, 0, 0.2)">
      <div style="margin-left: 50px">
              <el-upload
                ref="upload"
                :limit="1"
                :headers="upload.headers"
                :action="upload.url + '?engclass=' + upload.engclass"
                :on-progress="handleFileUploadProgress"
                :on-success="handleFileSuccess"
                :auto-upload="false"
                drag
                style="margin-left: 100px"
              >
<!--        <el-upload-->
<!--          ref="upload"-->
<!--          :limit="1"-->
<!--          :headers="upload.headers"-->
<!--          :action="upload.url"-->
<!--          :on-progress="handleFileUploadProgress"-->
<!--          :on-success="handleFileSuccess"-->
<!--          :auto-upload="false"-->
<!--          drag-->
<!--          style="margin-left: 100px"-->
<!--        >-->
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
      </div>
            <div>
              <div class="my_text" style="margin-bottom: 5px">请选择档案分类：</div>
<!--              <treeselect v-model="upload.engclass" :options="treemainOptions" :normalizer="normalizer" placeholder="请选择档案分类" class="my_box"/>-->
              <el-cascader
                style="width: 550px;"
                clearable
                v-model="upload.engclass"
                placeholder="请选择分类"
                :options="treemainOptions"
                :props="{ label: 'indexName', value: 'indexId' , emitPath:false,expandTrigger: 'hover'}"
                filterable
              ></el-cascader>
            </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="CheckSubmit">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {listInfo, getInfo, delInfo, addInfo, updateInfo} from "@/api/system/info";
import { listTreemain } from "@/api/system/treemain";
import {getToken} from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import moment from 'moment';

export default {
  name: "Info",
  components: {
    Treeselect,

  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文件上传表格数据
      infoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否导入弹出层
      imOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fileId: null,
        fileName: null,
        fileDopath: null
      },
      // 上传文件列表
      uploadedFiles: [],
      // 导入弹窗
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 档案分类
        engclass: -1,
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/info/importFilePath"
      },
      // 表单参数
      form: {},
      // 类别表单参数
      classForm: {},
      // 档案类别树选项
      treemainOptions: [],
      formData: {},
      // 表单校验
      rules: {}
    };
  },
  created() {
    this.getList();
    this.getTreeselect();
  },
  methods: {
    /** 查询文件上传列表 */
    getList() {
      this.loading = true;
      listInfo(this.queryParams).then(response => {
        this.infoList = response.rows;
        this.infoList = this.infoList.map(response => {
          const createTimeMoment = moment(response.createTime);
          response.createTime = createTimeMoment.format('YYYY-MM-DD HH:mm:ss');
          return response;
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    getTreeselect() {
      listTreemain().then(response => {
        this.treemainOptions = [];
        const data = { indexId: -1, indexName: '咸阳市档案分类', children: [] };
        data.children = this.handleTree(response.data, "indexId", "parentId");
        this.treemainOptions.push(data);
      })
    },

    /** 转换类别数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.indexId,
        label: node.indexName,
        children: node.children
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.upload.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        engFileId: null,
        fileId: null,
        fileName: null,
        fileDopath: null
      };
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.engFileId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加文件上传";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const engFileId = row.engFileId || this.ids
      getInfo(engFileId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改文件上传";
      });
    },

    // 文件上传前判断
    CheckSubmit() {
      const files = this.$refs.upload.uploadFiles
      if (this.upload.engclass === -1 || this.upload.engclass === undefined) {
        this.$modal.msgError('请选择档案分类后提交！')
      }
      else if (files.length === 0) {
        this.$modal.msgError('请上传档案文件！')
      } else {
        console.log(this.uploadedFiles)
        this.loading=true;
        this.submitFileForm()
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.engFileId != null) {
            updateInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const engFileIds = row.engFileId || this.ids;
      this.$modal.confirm('是否确认删除文件上传编号为"' + engFileIds + '"的数据项？').then(function () {
        return delInfo(engFileIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/info/export', {
        ...this.queryParams
      }, `info_${new Date().getTime()}.xlsx`)
    },

    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },

    /** 导入工程按钮操作 */


    handleImport() {
      this.upload.title = "导入工程";
      this.upload.open = true;
    },

    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.loading=false;
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },

    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 点击行触发，选中或不选中复选框
    handleRowClick(row, column, event) {
      this.$refs.multipleTable.toggleRowSelection(row);
    },

  }
};
</script>
<style>
.my_dialog {
  height: 600px;
}
</style>
